package com.toune.villager

import android.app.Application
import android.content.Context
import android.os.Looper
import android.util.Log
import androidx.multidex.MultiDex
import com.tamsiree.rxkit.RxActivityTool
import com.tamsiree.rxkit.RxSPTool
import com.toune.dealexception.dealException.Cockroach
import com.toune.dealexception.dealException.ExceptionHandler
import com.toune.dltools.DLTool
import com.toune.dltools.http.DLHttpConfig
import com.toune.villager.activity.LoginActivity
import com.toune.wxtool.WxTool

class MyApp : Application() {

    companion object {
        lateinit var context: Context
    }

    override fun onCreate() {
        super.onCreate()
        context = this
        DLTool.init(this)
            .setHttpConfig(
                DLHttpConfig.setDataStr("code", "msg", "").setSuccessCode(200)
                    .setTokenErrorCode(401, object : DLHttpConfig.TokenErrorListener {
                        override fun onTokenError() {
                            RxSPTool.putString(context, AppContant.SP_TOKEN, "")
                            RxActivityTool.skipActivityAndFinishAll(
                                RxActivityTool.currentActivity() as Context,
                                LoginActivity::class.java
                            )
                        }

                    })
            )
        WxTool.init(this, "wx1a1313d132164511", "")
    }

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        MultiDex.install(base)
    }

    /**
     * 打开错误信息抓取，防止软件崩溃
     */
    private fun openCrash(isOpen: Boolean) {
        if (isOpen) {
            Cockroach.install(this, object : ExceptionHandler() {
                override fun onUncaughtExceptionHappened(thread: Thread?, throwable: Throwable?) {
                    Log.e(
                        "AndroidRuntime",
                        "--->onUncaughtExceptionHappened:\$thread<---",
                        throwable
                    )
                }

                override fun onBandageExceptionHappened(throwable: Throwable) {
                    throwable.printStackTrace() //打印警告级别log，该throwable可能是最开始的bug导致的，无需关心
                }

                override fun onEnterSafeMode() {}
                override fun onMayBeBlackScreen(e: Throwable?) {
                    val thread = Looper.getMainLooper().thread
                    Log.e(
                        "AndroidRuntime",
                        "--->onUncaughtExceptionHappened:\$thread<---",
                        e
                    )
                }
            })
        }
    }
}